import cooApp, {
    Widget,
    basicWidgets,
    Util,
    ui,
    coolink,
    cooInfo,
} from 'coolink-ts'
import { Colors } from '../../config'
import func, { px } from '../../base/func'
import Center from '../../widgets/Center'
import baseInfo from '../../base/baseInfo'
import { showAutoHideToast } from '../../widgets/Toast'


const { Page, AppBar, Container, Text, Turntable, Button, Image } = basicWidgets

export default class WheelPage extends Widget<any, any> {

    state = {
        // 手机端数据
        contentObj: {
            awardNameList: [],
            awardRatioList: [],
            awardBgList: []
        },
        styleObj: {
            awardBgUrl: 'https://coolink.coocaa.com/applet/coo-turns/turnbg.png',
            bgWidth: 350.0,
            bgHeight: 350.0,
            contentWidth: 240.0,
            contentHeight: 240.0,
            secondUrl: 'https://coolink.coocaa.com/applet/coo-turns/center.png',
            secondWidth: 50.0,
            secondHeight: 50.0,
            circle: 4,
            fontSize: 16
        },
        result: 0,
        start: 0,
        showResultDialog: false,
        curResuleText: '',

        // TV端数据
        contentObj_tv: {
            "awardNameList": ["喝半杯", "真心话", "上家曝光", "下家曝光", "大家干杯", "男士喝光", "PASS", "女士干杯", "和异性交杯", "找人干杯", "自己唱首歌", "干一杯"],
            "awardRatioList": [1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12],
            "awardBgList": [Colors.Transparent, Colors.Lightgray, Colors.Transparent, Colors.Lightgray, Colors.Transparent, Colors.Lightgray, Colors.Transparent, Colors.Lightgray, Colors.Transparent, Colors.Lightgray, Colors.Transparent, Colors.Lightgray]
        },
        styleObj_tv: {
            awardBgUrl: 'https://coolink.coocaa.com/applet/coo-turns/turnbg.png',
            bgWidth: 350.0,
            bgHeight: 350.0,
            contentWidth: 240.0,
            contentHeight: 240.0,
            secondUrl: 'https://coolink.coocaa.com/applet/coo-turns/center.png',
            secondWidth: 50.0,
            secondHeight: 50.0,
            circle: 4,
            fontSize: 16
        },
        result_tv: 0,
        start_tv: 0,
        showResultDialog_tv: false,
        curResuleText_tv: '',


        // 通用数据
        backgroundGradient: {
            colors: [0xFF9C04D0, 0xFFFF60D5],
            type: 'linear',
            begin: 'centerLeft',
            end: 'centerRight'
        },
        boxShadow: {
            color: Colors.Black,
            blurRadius: 24,
            spreadRadius: 0,
        },
    }

    widgetDidMount() {
        cooApp.pageDidShow();
        // 开启组件联动
        this.enableLinking('my-homepage-component');
        this.setLinkCommandCallback(this.linkCommandProcess.bind(this));

        if (!this.isTv()) {
            this.showAwardsInPhone();
        } else {
            this.sendLinkCommand({ cmd: 'tv-ready' });  // 如果是电视机，则发送“电视机已经启动准备好”的消息
        }
    }


    pageDidPopNext() {
        let { getTurnsInfo } = baseInfo.turnsInfo;
        let _curAwards: any = getTurnsInfo();
        if (_curAwards) {
            Util.log('lxw 回到wheelPage1');
            let _newContentObj = {
                awardNameList: [],
                awardRatioList: [],
                awardBgList: [],
            };
            for (let i = 0; i < _curAwards.awardNameList.length; i++) {
                _newContentObj.awardNameList[i] = _curAwards.awardNameList[i];
                // _newContentObj.awardRatioList[i] = Number(_curAwards.awardRatioList[i]);
                _newContentObj.awardRatioList[i] = 1 / _curAwards.awardNameList.length;
                // _newContentObj.awardBgList[i] = Number(_curAwards.awardBgList[i]);
                _newContentObj.awardBgList[i] = Number((i % 2 == 0) ? Colors.Transparent : Colors.Lightgray);
            }
            this.reverseFunc(_newContentObj, 1)
        } else {
            Util.log('lxw 回到wheelPage2');
        }
    }
    widgetDidUnmount(): void {
    }
    isTV() {
        if (cooInfo.infos?.systemInfo?.os && (cooInfo.infos.systemInfo.os.indexOf('ccos') >= 0)) {
            return true;
        }
        return false;
    }

    beforeLinkView() {
        coolink.protocol.isConnected().then((res) => {
            if (res.code == 0 && res.connected) {
                // 判断手机端是否连接设备
                this.startTv();
            } else {
                func.getRemoteDeviceInfos(showAutoHideToast, '设备离线中，请检查设备是否断电断网');
            }
        }).catch((err) => {
            func.getRemoteDeviceInfos(showAutoHideToast, '设备离线中，请检查设备是否断电断网');
        });
    }

    showAwardsInPhone = async () => {
        let _localAwards = await coolink.storage.getKey("singleAwards");
        Util.log("lxw showAwardsInPhone localAwards:", _localAwards.value)
        if (_localAwards.value) {
            let _localContentObj = {
                awardNameList: [],
                awardRatioList: [],
                awardBgList: [],
            };
            for (let i = 0; i < JSON.parse(_localAwards.value).awardNameList.length; i++) {
                _localContentObj.awardNameList[i] = JSON.parse(_localAwards.value).awardNameList[i];
                _localContentObj.awardRatioList[i] = (1 / JSON.parse(_localAwards.value).awardNameList.length);
                _localContentObj.awardBgList[i] = Number((i % 2 == 0) ? Colors.Transparent : Colors.Lightgray);

                // _localContentObj.awardRatioList[i] = Number(JSON.parse(_localAwards.value).awardRatioList[i]);
                // _localContentObj.awardBgList[i] = Number(JSON.parse(_localAwards.value).awardBgList[i]);
            }
            this.reverseFunc(_localContentObj, 0)
        } else {
            let _defaultContentObj = {
                "awardNameList": ["喝半杯", "真心话", "上家曝光", "下家曝光", "大家干杯", "男士喝光", "PASS", "女士干杯", "和异性交杯", "找人干杯", "自己唱首歌", "干一杯"],
                "awardRatioList": [1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12, 1 / 12],
                "awardBgList": [Colors.Transparent, Colors.Lightgray, Colors.Transparent, Colors.Lightgray, Colors.Transparent, Colors.Lightgray, Colors.Transparent, Colors.Lightgray, Colors.Transparent, Colors.Lightgray, Colors.Transparent, Colors.Lightgray]
            }
            this.reverseFunc(_defaultContentObj, 0)
        }
    }
    reverseFunc(obj: any, num: any) {
        Util.log("lxw reverseFunc:" + obj.awardNameList.length);
        let reverseObj = {
            awardNameList: [],
            awardRatioList: [],
            awardBgList: []
        }
        // 
        for (let i = 0; i < obj.awardNameList.length; i++) {
            reverseObj.awardNameList[i] = obj.awardNameList[obj.awardNameList.length - i - 1];
            // reverseObj.awardRatioList[i] = obj.awardRatioList[obj.awardNameList.length - i - 1];
            reverseObj.awardRatioList[i] = 1 / obj.awardNameList.length;
            reverseObj.awardBgList[i] = obj.awardBgList[obj.awardNameList.length - i - 1];
        }
        Util.log("lxw reverseFunc2:" + JSON.stringify(reverseObj));
        this.setState({ contentObj: reverseObj })
        if (num == 1) {
            // 更新TV端数据
            this.setTvState({ contentObj_tv: reverseObj })
        }
    }
    showTurnsStyle() {
        // 显示转盘样式

    }
    onStartDraw() {
        let _result = this.rand(0, this.state.contentObj.awardNameList.length);
        Util.log("lxw onStartDraw:", _result);
        this.setState({ result: _result, start: 1 });
        this.setTvState({ result_tv: _result, start_tv: 1 })
    }
    rand(min: number, max: number) {
        return Math.floor(Math.random() * (max - min)) + min;
    }
    getResultInfo(result: any) {
        let _curResuleText = this.state.contentObj.awardNameList[this.state.contentObj.awardNameList.length - result - 1];
        Util.log("lxw getResultInfo:", result, _curResuleText);

        if (this.isTV()) {
            // TV端状态改变，显示弹窗
            // this.setState({ start: 0 });
            // this.setState({ curResuleText: _curResuleText });
        } else {
            // 手机端状态改变，显示弹窗
            this.setState({ start: 0, curResuleText: _curResuleText, showResultDialog: true });
        }
    }

    hiddenDialog() {
        Util.log("lxw hiddenDialog=====================new");
        this.setState({ showResultDialog: false });
    }
    pushToTv() {
        Util.log("lxw pushToTv");
        this.beforeLinkView();
    }
    gotoEditPage() {
        this.setState({ start: 0 });
        cooApp.pushPage('editPage');
    }

    startTv() {
        let random1: string = (parseInt((Math.random() * 10000000).toString())).toString();
        let random2: string = (parseInt((Math.random() * 10000000).toString())).toString();
        let random3: string = (parseInt((Math.random() * 10000000).toString())).toString();
        let random4: string = (parseInt((Math.random() * 10000000).toString())).toString();
        coolink.protocol.sendMessage({
            "id": random1 + random2 + random3 + random4,
            "content": JSON.stringify({
                cmd: "start_tv_mini_app",
                content: JSON.stringify({
                    "mp_alias": "转盘游戏",
                    // "mp_bundle": "https://coolink.coocaa.com/applet/coo-turns/bundle_1.0.0.js",
                    "mp_bundle": "http://172.20.146.120:12345/bundle.js",
                    "mp_code": "coolink-mobile-applet/turns-table",
                    "dev_name": "深圳市酷开网络科技股份有限公司",
                    "dev_type": "enterprise",
                    "mp_id": 3,
                    "mp_intro": "通过大屏联动，为热爱游戏的人提供更多垂直、多元的游戏场景，与家人们互动起来！",
                    "mp_logo": "https://coolink.coocaa.com/applet/coo-turns/logo.webp",
                    "mp_name": "转盘游戏",
                    "mp_version": "1.0.1"
                }),
            }),
            //"remoteClientID": "tv-app/com.tianci.movieplatform",
            "appTargetID": "coocaa-link-server",
            "appSourceID": "coolink-mobile-applet/turns-table",
            "type": "TEXT",
            "extra": {},
            "reply": false,
            "broadcast": false
        } as any);
    }

    linkCommandProcess(msg, raw) {
        Util.log('linkCommandProcess: ' + JSON.stringify(msg));
        if (this.isTV()) {
            // 电视机处理逻辑
        } else {
            if (msg?.cmd == 'tv-ready') {
                // 设置TV端相关state
                Util.log("tv-ready", this.state.contentObj)
                let a = this.state.contentObj;
                this.setTvState({ contentObj_tv: a })
            }
        }

    }

    render() {
        Util.log("lxw render", this.state.contentObj.awardNameList, this.state.contentObj.awardRatioList, this.state.contentObj.awardBgList);
        const appbarHeight = ui.appbarHeight;
        const statusBarHeight = Math.round(ui.statusBarHeight);
        const bottomBarHeight = ui.bottomBarHeight;
        const clientHeight = ui.screenHeight - statusBarHeight - appbarHeight - bottomBarHeight;
        return (
            this.isTV() ?
                (
                    <Page>
                        <Container relative={true} width={ui.screenWidth} height={ui.screenHeight}>
                            <Center absolute={{ top: 0, left: 0 }} width={ui.screenWidth} height={ui.screenHeight} backgroundColor={Colors.Darkgray}>
                                {this.state.contentObj_tv.awardNameList.length > 0 &&
                                    <Turntable height={700}
                                        awardNameList={this.state.contentObj_tv.awardNameList}
                                        awardRatioList={this.state.contentObj_tv.awardRatioList}
                                        awardBgColorList={this.state.contentObj_tv.awardBgList}
                                        awardBgUrl={this.state.styleObj.awardBgUrl}
                                        bgWidth={this.state.styleObj.bgWidth * 2}
                                        bgHeight={this.state.styleObj.bgHeight * 2}
                                        contentWidth={this.state.styleObj.contentWidth * 2}
                                        contentHeight={this.state.styleObj.contentHeight * 2}
                                        secondUrl={this.state.styleObj.secondUrl}
                                        secondWidth={this.state.styleObj.secondWidth * 2}
                                        secondHeight={this.state.styleObj.secondHeight * 2}
                                        circle={this.state.styleObj.circle}
                                        fontSize={28}
                                        result={this.state.result_tv}
                                        start={this.state.start_tv}
                                        onStopBack={(resule) => {
                                            return new Promise(resolve => {
                                                this.getResultInfo(resule)
                                                resolve()
                                            })
                                        }}
                                    >
                                    </Turntable>
                                }
                            </Center>
                        </Container>
                    </Page>
                )
                :
                <Page>
                    <Container relative={true} width={ui.screenWidth} height={ui.screenHeight}>
                        <Image absolute={{ top: 0, left: 0 }} fit="fill" src='https://coolink.coocaa.com/applet/coo-turns/wheelpageBg.png' height={ui.screenHeight} width={ui.screenWidth}></Image>
                        <Container relative={true} absolute={{ top: 0, left: 0 }} width={ui.screenWidth} height={clientHeight} justifyContent="center" alignItems="center">
                            <Center width={ui.screenWidth} height={px(400)}>
                                {
                                    this.state.contentObj.awardNameList.length > 0 &&
                                    <Turntable height={400}
                                        awardNameList={this.state.contentObj.awardNameList}
                                        awardRatioList={this.state.contentObj.awardRatioList}
                                        awardBgColorList={this.state.contentObj.awardBgList}
                                        awardBgUrl={this.state.styleObj.awardBgUrl}
                                        bgWidth={this.state.styleObj.bgWidth}
                                        bgHeight={this.state.styleObj.bgHeight}
                                        contentWidth={this.state.styleObj.contentWidth}
                                        contentHeight={this.state.styleObj.contentHeight}
                                        secondUrl={this.state.styleObj.secondUrl}
                                        secondWidth={this.state.styleObj.secondWidth}
                                        secondHeight={this.state.styleObj.secondHeight}
                                        circle={this.state.styleObj.circle}
                                        fontSize={this.state.styleObj.fontSize}
                                        result={this.state.result}
                                        start={this.state.start}
                                        onStopBack={(resule) => {
                                            return new Promise(resolve => {
                                                this.getResultInfo(resule)
                                                resolve()
                                            })
                                        }}
                                    >
                                    </Turntable>
                                }
                            </Center>

                            <Button
                                width={px(270)}
                                height={px(56)}
                                borderRadius={px(25)}
                                justifyContent="center" alignItems="center"
                                backgroundGradient={this.state.backgroundGradient as any}
                                boxShadow={this.state.boxShadow}
                                onTap={() => this.pushToTv()}
                            >
                                <Text text="电视联动" color={0xffffffff} size={px(20)}></Text>
                            </Button>
                            <Button
                                width={px(270)}
                                height={px(56)}
                                borderRadius={px(25)}
                                margin={{ top: px(20) }}
                                justifyContent="center" alignItems="center"
                                backgroundGradient={this.state.backgroundGradient as any}
                                boxShadow={this.state.boxShadow}
                                onTap={() => this.onStartDraw()}
                            >
                                <Text text="开始游戏" color={0xffffffff} size={px(20)}></Text>
                            </Button>
                            <Button
                                width={px(270)}
                                height={px(56)}
                                borderRadius={px(25)}
                                margin={{ top: px(20) }}
                                justifyContent="center" alignItems="center"
                                backgroundGradient={this.state.backgroundGradient as any}
                                boxShadow={this.state.boxShadow}
                                onTap={() => this.gotoEditPage()}
                            >
                                <Text text="编辑转盘内容" color={0xffffffff} size={px(20)}></Text>
                            </Button>

                            {
                                this.state.showResultDialog &&
                                <Container absolute={{ left: 0, top: 0 }} backgroundColor={0xb2000000} width={ui.screenWidth} height={ui.screenHeight} relative={true} onTap={() => this.hiddenDialog()}>
                                    <Container relative={true} width={px(270)} height={px(120)} absolute={{ left: px(53), top: px(360) }} backgroundColor={Colors.White} borderRadius={10}>
                                        <Center width={px(270)} height={px(60)} absolute={{ top: 0 }}>
                                            <Text color={0xff000000} size={px(16)} align="center">{this.state.curResuleText}</Text>
                                        </Center>
                                        <Center row width={px(270)} height={px(60)} absolute={{ top: px(60) }} border={{ style: 'solid', width: 1, color: 0xff000000, side: ['top'] }}>
                                            <Button width={px(134.5)} height={px(60)} onTap={() => { this.hiddenDialog() }}><Text color={0xff000000} size={px(17)}>知道了</Text></Button>
                                        </Center>
                                    </Container>showResultDialog
                                </Container>
                            }
                        </Container>
                    </Container>
                </Page >
        )
    }
}


